<template>
  <a-modal
    @cancel="modalClose"
    :visible="loginModalVisible"
    layout="horizontal"
    width="440px"
    wrapClassName="login-modal"
    :footer="null"
    :destroyOnClose="true"
    :maskClosable="false"
    :zIndex="3000"
  >
    <div class="tab-group">
      <span
        :class="{ active: loginTabKey === '1' }"
        @click="() => (this.loginTabKey = '1')"
        >账号登录</span
      >
      <span
        :class="{ active: loginTabKey === '2' }"
        @click="() => (this.loginTabKey = '2')"
        >验证码登录</span
      >
    </div>
    <a-tabs
      v-model="loginTabKey"
      default-active-key="1"
      @change="loginTabChange"
    >
      <a-tab-pane key="1" tab="">
        <a-form-model ref="loginForm" :model="loginForm" :rules="rules">
          <a-form-model-item prop="username">
            <a-input
              v-model="loginForm.username"
              autocomplete="off"
              placeholder="手机号"
              @focus="clearValidate('loginForm', 'username')"
            >
              <template slot="prefix">
                <YxpIcon type="iconlogin_icon_account" />
                <span>账号</span>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="password">
            <a-input
              v-model="loginForm.password"
              type="password"
              autocomplete="off"
              placeholder="密码"
              @focus="clearValidate('loginForm', 'password')"
            >
              <template slot="prefix">
                <YxpIcon type="iconlogin_icon_password" />
                <span>密码</span>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="read" label="">
            <a-checkbox v-model="loginForm.read">
              我已阅读并接受
              <a @click="openUrl('/registration')">《用户注册协议》</a
              ><a @click="openUrl('/privacyprotection')">《隐私权保护政策》</a>
            </a-checkbox>
          </a-form-model-item>
          <a-button
            type="primary"
            shape="round"
            size="large"
            block
            html-type="submit"
            @click="loginSubmit"
          >
            登录
          </a-button>
          <p class="modal-bottom clear">
            <span class="fl forget" @click="forgetPass">忘记密码</span>
<!--            <router-link to="/register" class="fr to-register"-->
<!--              >没有账号? 去注册</router-link-->
<!--            >-->
          </p>
        </a-form-model>
      </a-tab-pane>
      <a-tab-pane key="2" tab="">
        <a-form-model
          ref="fastLoginForm"
          :model="fastLoginForm"
          :rules="rulesFast"
        >
          <a-form-model-item prop="mobile">
            <a-input
              v-model="fastLoginForm.mobile"
              autocomplete="off"
              placeholder="手机号"
              @focus="clearValidate('fastLoginForm', 'mobile')"
            >
              <template slot="prefix">
                <YxpIcon type="iconmobile"></YxpIcon>
                <span>手机号</span>
              </template>
            </a-input>
          </a-form-model-item>
          <a-form-model-item prop="code">
            <a-input
              v-model="fastLoginForm.code"
              autocomplete="off"
              placeholder="验证码"
              @focus="clearValidate('fastLoginForm', 'code')"
            >
              <template slot="prefix">
                <YxpIcon type="iconregister_icon_yanzhengma1" />
                <span>验证码</span>
              </template>
            </a-input>
            <a-button
              type="primary"
              shape="round"
              :disabled="disabled"
              @click="getVerifyCode"
              >{{ btnTitle }}</a-button
            >
          </a-form-model-item>
          <a-form-model-item prop="read" label="">
            <a-checkbox v-model="fastLoginForm.read">
              我已阅读并接受
              <a @click="openUrl('/registration')">《用户注册协议》</a
              ><a @click="openUrl('/privacyprotection')">《隐私权保护政策》</a>
            </a-checkbox>
          </a-form-model-item>
          <a-button
            type="primary"
            shape="round"
            size="large"
            block
            html-type="submit"
            @click="fastLoginSubmit"
          >
            登录
          </a-button>
          <p class="modal-bottom clear">
            <span class="fl forget" @click="forgetPass">忘记密码</span>
<!--            <router-link to="/register" class="fr to-register"-->
<!--              >没有账号? 去注册</router-link-->
<!--            >-->
          </p>
        </a-form-model>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import mTypes from "@/store/mutationsTypes";
import { Modal, FormModel, Input, Checkbox, Tabs } from "ant-design-vue";
import { sendSms, userLogin, fastLogin } from "@/services";
import { validatePhone, validatePass } from "@/utils/form-validate";
import _ from "lodash";
import { openBrowser } from "@/utils/tools";
import ROUTER_MAP from "@/router/router-map";
import { getPosition } from '../../../utils/tools'

export default {
  name: "LoginModal",
  components: {
    AModal: Modal,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ACheckbox: Checkbox,
    ATabs: Tabs,
    ATabPane: Tabs.TabPane
  },
  data() {
    return {
      loginTabKey: "1",
      lng:'',
      lat:'',
      loginForm: {
        username: "",
        password: "",
        read: true
      },
      fastLoginForm: {
        username: "",
        password: "",
        read: true
      },
      rules: {
        username: [{ validator: validatePhone, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        read: [{ required: true, message: "请确认勾选阅读协议" }]
      },
      rulesFast: {
        mobile: [{ validator: validatePhone, trigger: "blur" }],
        code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
        read: [{ required: true, message: "请确认勾选阅读协议" }]
      },
      disabled: false,
      btnTitle: "获取验证码"
    };
  },
  computed: {
    ...mapState({
      loginModalVisible: state => state.loginModalVisible
    })
  },
  watch: {},
  methods: {
    ...mapMutations([mTypes.loginModal, mTypes.forgetModal]),
    openUrl(remoteUrl) {
      const url = `/#${remoteUrl}`;
      openBrowser(url);
    },
    modalClose() {
      this.$store.commit(mTypes.loginModal, false);
    },
    loginSubmit(e) {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          this.loginForm.lat = this.lat;
          this.loginForm.lng = this.lng;
          let res = await userLogin(_.omit(this.loginForm, "read"));
          if (res.code === 1) {
            this.setFrameLoginInfo(res.data);
            this.$message.success("登录成功");
            this[mTypes.loginModal](false);
            if (res.data.status === 4) {
              this.$router.push({
                path: "/register",
                query: { step: "2" }
              });
            } else {
              if (this.$route.name === "YxpRoom") {
                this.$router.push("/mycourse");
              } else if ([ROUTER_MAP.register, ROUTER_MAP.teacherLogin].includes(this.$route.name)) {
                // 注册页 助教登录页
                this.$router.push("/mycourse");
              }
            }
          }
        }
      });
    },
    fastLoginSubmit() {
      this.$refs.fastLoginForm.validate(async valid => {
        if (valid) {
          this.fastLoginForm.lat = this.lat;
          this.fastLoginForm.lng = this.lng;
          let res = await fastLogin(_.omit(this.fastLoginForm, "read"));
          if (res.code === 1) {
            this.setFrameLoginInfo(res.data);
            this.$message.success("登录成功");
            this[mTypes.loginModal](false);
            if (res.data.status === 4) {
              this.$router.push({
                path: "/register",
                query: { step: "2" }
              });
            } else {
              if (this.$route.name === "YxpRoom") {
                // 教室内登陆失效
                this.$router.push("/mycourse");
              } else if ([ROUTER_MAP.register, ROUTER_MAP.teacherLogin].includes(this.$route.name)) {
                // 注册页 助教登录页
                this.$router.push("/mycourse");
              }
            }
          }
        }
      });
    },
    loginTabChange(value) {},
    forgetPass() {
      this[mTypes.loginModal](false);
      this[mTypes.forgetModal]({ visible: true });
    },
    getVerifyCode(e) {
      this.$refs.fastLoginForm.validateField(["mobile"], async valid => {
        if (!valid) {
          this.validateBtn();
          let code = await sendSms({
            username: this.fastLoginForm.mobile,
            type: 5
          });
        }
      });
    },
    validateBtn() {
      //倒计时
      let time = 60;
      this.disabled = true;
      let timer = setInterval(() => {
        if (time == 0) {
          clearInterval(timer);
          this.disabled = false;
          this.btnTitle = "获取验证码";
        } else {
          this.btnTitle = time + "秒后重试";
          this.disabled = true;
          time--;
        }
      }, 1000);
    },
    setFrameLoginInfo(userInfo) {
      let frame = document.getElementById("pad-frame");
      sessionStorage.setItem("student_doubleminus",userInfo.doubleminus_type)
      if (frame) {
        frame.contentWindow.postMessage(
          {
            cmd: "login",
            msg: {
              access_token: userInfo.access_token,
              userInfo: userInfo
            }
          },
          "*"
        );
      }
    },
    clearValidate(form, filed) {
      this.$refs[form].clearValidate(filed);
    },
  },
  created() {
  },
  mounted() {
    //进入房间  判断是否是正式学生  若是正式学生  则要校验经纬度
    let positon = getPosition().then((position1) => {
      this.showLocation(position1)
      this.lat = position1.lat;
      this.lng = position1.lon;
    })
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {}
};
</script>
<style lang="less" scoped>
//@import url(); 引入公共css类
.login-modal {
  .modal-bottom {
    margin-top: 20px;
    .forget,
    .to-register {
      color: #999;
      cursor: pointer;
    }
  }
  .tab-group {
    font-size: 16px; /* no */
    font-weight: 700;
    color: #cbcbcb;
    margin-bottom: 40px;
    span {
      position: relative;
      cursor: pointer;
      margin-right: 40px;
      &:hover {
        color: #7e7e7e;
      }
    }
    .active {
      color: @primary-color;
      &:hover {
        color: @primary-color;
      }
      &::after {
        content: "";
        position: absolute;
        height: 4px; /* no */
        width: 20px; /* no */
        border-radius: 2px; /* no */
        left: 50%;
        bottom: -6px; /* no */
        transform: translateX(-50%);
        background-color: @primary-color;
      }
    }
  }

  /deep/ .ant-form-item-children {
    display: flex;
  }
}
</style>
